package com.gss.module.translate;

import com.gss.module.translate.chromedriver.BaiduTranslator;
import com.gss.module.translate.chromedriver.BingTranslator;
import com.gss.module.translate.chromedriver.GoogleTranslator;
import com.gss.module.translate.chromedriver.YoudaoTranslator;
import com.gss.module.translate.constants.ModeType;
import com.gss.module.translate.constants.TransType;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * @author DYang
 * @date 2023/6/6
 */
public class TranslationHandle {

    /**
     * 翻译器集合
     */
    private Map<String,Translation> translatorMap = new HashMap<>();

    /**
     * 翻译数据
     * @param mode       翻译模式
     * @param trans      翻译器
     * @param inputStr  翻译内容
     * @param timeout   执行时间
     * @return
     */
    public String trans(String mode,String trans,String inputStr,long timeout){
        //获取翻译器
        Translation translation = this.getTranslator(mode,trans);
        //翻译
        translation.inputText(inputStr,timeout);
        //获取结果
        String transOut = translation.getTransOut();
        return transOut;
    }

    /**
     * 关闭翻译器
     * @param mode 模式
     * @param trans 翻译器
     */
    public void closeTrans(String mode,String trans){
        Translation translation = this.getTranslator(mode, trans);
        translation.closeTrans();
        translatorMap.remove(mode + "_" + trans);
    }

    /**
     * 获取翻译器
     * @param mode
     * @param trans
     * @return
     */
    private Translation getTranslator(String mode, String trans) {
        String key = mode + "_" + trans;
        Translation translation = translatorMap.get(key);
        if (translation != null) {
            return translation;
        }
        ModeType modeType = ModeType.getModeType(mode);
        TransType transType = TransType.getTransType(trans);
        switch (modeType) {
            case CHROME_DRIVER: {
                switch (transType) {
                    case BAIDU_TRANS:
                        translation = new BaiduTranslator().getInstance();
                        break;
                    case BING_TRANS:
                        translation = new BingTranslator().getInstance();
                        break;
                    case GOOGLE_TRANS:
                        translation = new GoogleTranslator().getInstance();
                        break;
                    case YOUDAO_TRANS:
                        translation = new YoudaoTranslator().getInstance();
                        break;
                    default:
                        break;
                }
            }
            break;
            default:
                break;
        }
        if (translation != null) {
            translatorMap.put(key,translation);
            return translation;
        }
        return null;
    }

}
